import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Website } from './entities/website.entity';
import { PageView } from './entities/page-view.entity';

@Injectable()
export class SessionService {
  constructor(
    @InjectRepository(Website)
    private websiteRepository: Repository<Website>,
    @InjectRepository(PageView)
    private pageViewRepository: Repository<PageView>,
  ) {}

  async getSessionDetails(sessionId: string): Promise<any> {
    try {
      const visits = await this.pageViewRepository.find({
        where: { sessionId },
        order: { createdAt: 'ASC' },
        relations: ['website']
      });
      if (visits.length === 0) {
        throw new Error('会话不存在');
      }
      const firstVisit = visits[0];
      const lastVisit = visits[visits.length - 1];
      const duration = lastVisit.createdAt.getTime() - firstVisit.createdAt.getTime();
      const durationInMinutes = Math.round(duration / 60000);
      const websiteId = firstVisit.websiteId;
      const website = await this.websiteRepository.findOne({ where: { id: websiteId } });
      const pagesWithDuration = [];
      for (let i = 0; i < visits.length; i++) {
        const visit = visits[i];
        const nextVisit = i < visits.length - 1 ? visits[i + 1] : null;
        let timeOnPage = 0;
        if (nextVisit) {
          timeOnPage = (nextVisit.createdAt.getTime() - visit.createdAt.getTime()) / 1000;
        }
        pagesWithDuration.push({
          ...visit,
          timeOnPage
        });
      }
      return {
        sessionId,
        website,
        stats: {
          pageViews: visits.length,
          duration: durationInMinutes,
          startTime: firstVisit.createdAt,
          endTime: lastVisit.createdAt,
          referrer: firstVisit.referrer,
          browser: firstVisit.browser,
          os: firstVisit.os,
          device: firstVisit.device,
          country: firstVisit.country,
          city: firstVisit.city
        },
        pages: pagesWithDuration
      };
    } catch (error) {
      throw new Error(`获取会话详情失败: ${error.message}`);
    }
  }
} 